package com.example.materialcostsystembackend.controller;

import com.example.materialcostsystembackend.dto.OrderRequest;
import com.example.materialcostsystembackend.model.OrderItemDetail;
import com.example.materialcostsystembackend.model.OrderSummary;
import com.example.materialcostsystembackend.service.OrderService;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/orders")
@CrossOrigin(origins = "*")
public class OrderController {
    private final OrderService orderService;

    public OrderController(OrderService orderService) {
        this.orderService = orderService;
    }
    @GetMapping("/exists")
    public ResponseEntity<?> checkExists(@RequestParam String orderNumber) {
        boolean exists = orderService.existsByOrderNumber(orderNumber);
        return ResponseEntity.ok().body(java.util.Map.of("exists", exists));}
    @PostMapping
    @Transactional

    public ResponseEntity<?> saveOrder(@RequestBody OrderRequest orderRequest) {
        orderService.saveOrder(orderRequest);
        if (orderRequest.getOrderNumber() == null || orderRequest.getOrderNumber().trim().isEmpty()) {
            throw new IllegalArgumentException("订单编号不能为空");
        }
        return ResponseEntity.ok().build();


    }

    @GetMapping
    public List<OrderSummary> getAllOrders() {
        return orderService.getAllOrders();
    }

    @DeleteMapping("/{orderNumber}")
    public void deleteOrder(@PathVariable String orderNumber) {
        orderService.deleteOrder(orderNumber);
    }

    @GetMapping("/{orderNumber}/items")
    public List<OrderItemDetail> getOrderItems(@PathVariable String orderNumber) {
        return orderService.getOrderItems(orderNumber);
    }
}